import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Task {
    public static void main(String[] args) throws IOException {
        String filename = "lesson9/task2/resource/data.txt";
        readFileAll(filename);
        System.out.println("----------------");
        readFileWithBuffer(filename);
        System.out.println("----------------");
        readFile(filename);
    }

    /**
     * 一次性读取文件所有字节
     * @param filename 文件名
     * @throws IOException
     */
    public static void readFileAll(String filename) throws IOException {
        InputStream is = new FileInputStream(filename);
        byte[] bytes = is.readAllBytes();
        System.out.println(new String(bytes));
        is.close();
    }

    /**
     * 定义并使用buffer缓冲区读取文件，加快速度
     * @param filename
     * @throws IOException
     */
    public static void readFileWithBuffer(String filename) throws IOException {
        InputStream is = new FileInputStream(filename);

        byte[] buffer = new byte[3];
        int len; // 记录每次读取的字节数
        while ((len = is.read(buffer)) != -1) {
            String s = new String(buffer, 0, len);
            System.out.print(s);
        }
        System.out.println();
        // 释放系统资源
        is.close();
    }

    /**
     * 一次读取一个字节
     * @param filename
     * @throws IOException
     */
    public static void readFile(String filename) throws IOException {
        InputStream is = new FileInputStream(filename);

        int b;
        while ((b = is.read()) != -1) {
            System.out.print((char) b);
        }
        System.out.println();
        // 释放系统资源
        is.close();
    }
}